var moment = require('moment');

const dataScreenStorage = require('../memStorage/dataScreenStorage.js')

const orderPushDuration = 300; // 订单推送间隔
const orderPushDelay = 30 * 1000; // 订单推送延时， 为了兼容数据延时和降噪，所以做了30秒延时

module.exports = function(sokcet){
    return new Promise((res, rej)=>{
        sokcet.on('connection', function(client){

            const agentSupports = [
                "data-screen-client-ios",
                "data-screen-client-android"
            ];
            
            if(!agentSupports.indexOf(client.request.headers["xsyx-app-agent"])>=0) {
                client.emit('authority')
                client.disconnect();
                return;
            }

            setInterval(()=>{
                client.emit('sold_area_gmv', dataScreenStorage.data.areaGmv)
            }, 1500)
            setInterval(()=>{
                client.emit('sold_out_rate', dataScreenStorage.data.soldOutRate)
            }, 1500)
            setInterval(()=>{
                // const delay = 30; // 延迟秒数
                const tsstart = Date.now() - orderPushDelay;
                const tsend = tsstart + orderPushDuration;
                const orderList = dataScreenStorage.data.orderlist;
                const listLength = orderList.length;
                for(let i = 0; i<listLength; i++){
                    const orderTime = new Date(orderList[i].下单时间).getTime();
                    if(orderTime < tsend && orderTime >= tsstart){
                        client.emit('order', orderList[i])
                    }
                }
            }, orderPushDuration) // 必须等于 1s 因为遍历的时间
        })
    })
    // sokcet.on('message', function(client){

    // })   
}